<?php

/*
采购订单列表
*/
namespace Modules\Purchasing\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Models\Material;

class PurchaseorderReget
{
    /*
    数据处理
    */
    public static function processingdata()
    {
        $fmaterialid = Purchaseorderschedule::select('id','fmaterialid')->get()->toArray();
      
            foreach ($fmaterialid as $k=>$v){
                $data = Material::select('fmaterial')->where('fnumber',$v['fmaterialid'])->first();
                if(!empty($data)){
                Purchaseorderschedule::where('id',$v['id'])->update(['fmasterid'=>$data['fmaterial']]);    
                }
                
            }

    }


    /*
    数据列表
    */
    public static function list($data = [])
    {
        return self::getBuilder($data)->paginate($data['limit'] ?? 100);
    }


     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
       
        $builder = Purchaseorder::query()->with('detailscheckAll');
        if(isset($data['fbillno'])) {
            $builder->where('fbillno', 'like', "%{$data['fbillno']}%");
        }
        if (isset($data['fsupplierid_name'])) {
            $builder->where('fsupplierid_name', 'like', "%{$data['fsupplierid_name']}%");
        }

        if (isset($data['fdocumentstatus'])) {
            $builder->where('fdocumentstatus', $data['fdocumentstatus']);
        }

        if (isset($data['fsupplierid_number'])) {
            $builder->where('fsupplierid_number', $data['fsupplierid_number']);
        }

        if (isset($data['state'])) {
            $builder->where('state', $data['state']);
        }
        
        
        $builder->orderBy('id', 'desc');

        return $builder;
    }
 /*
    数据列表
    */
    public static function listTwo($data = [])
    {
        return self::getBuilderTwo($data)->paginate($data['limit'] ?? 100);
    }
     /**
     *弹窗查询
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilderTwo(array $data = []): Builder
    {
      
        // $builder = Purchaseorder::query()->with('detailscheckAll');
        $builder = Purchaseorder::query();
        $builder->join('purchaseorderschedule as purchaseorderschedule', 'purchaseorderschedule.purchaseorder_id', '=', 'purchaseorder.id');
         
        if(isset($data['fbillno'])) {
            $builder->where('purchaseorder.fbillno', 'like', "%{$data['fbillno']}%");
        }
        if (isset($data['fsupplierid_name'])) {
            $builder->where('purchaseorder.fsupplierid_name', 'like', "%{$data['fsupplierid_name']}%");
        }

        if (isset($data['fdocumentstatus'])) {
            $builder->where('purchaseorder.fdocumentstatus', $data['fdocumentstatus']);
        }

        if (isset($data['fsupplierid_number'])) {
            $builder->where('purchaseorder.fsupplierid_number', $data['fsupplierid_number']);
        }

      
        if (isset($data['fownerid_name'])) {   
            $builder->where('purchaseorderschedule.fownerid_name', $data['fownerid_name']);
        }

        //显示隐藏做好的采购订单
        if (isset($data['state'])) {
            // if($data['state']==0){
            //     $builder->where('purchaseorderschedule.state', $data['state']);
            // }

           $builder->where('purchaseorderschedule.state', $data['state']);
        }
        
        
        $builder->orderBy('purchaseorder.id', 'desc');

        return $builder;
    }

    /*
    数据添加方法
    */
    public static function create(array $data)
    {
        
        $Purchaseorder = new Purchaseorder;
        return self::createOrSave($Purchaseorder, $data);
    }

    //数据添加方法
    public static function createOrSave(Purchaseorder $Purchaseorder,$data)
    {
        if(empty($data['FEntry'])){
            throw new FailedException('亲！物料不能为空');
        }
        try {
            //开始起事务
            DB::beginTransaction();
            $PurchaseorderData = [];

            $PurchaseorderData['fid'] = $data['fid'];
            $PurchaseorderData['fbillno'] = $data['fbillno'];
            $PurchaseorderData['fbusinesstype'] = $data['fbusinesstype'];
            $PurchaseorderData['fpurchaseorgid_number'] = $data['fpurchaseorgid_number'];
            $PurchaseorderData['fpurchaseorgid_name'] = $data['fpurchaseorgid_name'];
            $PurchaseorderData['fsupplierid_number'] = $data['fsupplierid_number'];
            $PurchaseorderData['fsupplierid_name'] = $data['fsupplierid_name'];
            $PurchaseorderData['fdocumentstatus'] = $data['fdocumentstatus'];
            $PurchaseorderData['fforbidstatus'] = $data['fforbidstatus'];
            $PurchaseorderData['fprovidercontactid'] = $data['fprovidercontactid'];
            $PurchaseorderData['fproviderphone'] = $data['fproviderphone'];
            // $PurchaseorderData['fmasterid'] = $data['fmasterid'];
            // $PurchaseorderData['fownertypeid'] = $data['fownertypeid'];
            $Purchaseorder->fill($PurchaseorderData);
            $Purchaseorder->save();
            
            $Purchaseorder->detailscheckAll()->createMany($data['FEntry']);
           
            DB::commit();
            return '数据添加成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据添加失败，服务器上火星了请联系技术处理');
        }
    }
    
    //修改
    public static function createUpdate($data)
    {
 

                $datares  = Purchaseorder::query()->select('id')->where('fid',$data['fid'])->first();
                if(empty( $datares)){throw new FailedException('亲，修改数据失败，没有该单号。');}
            try {
                //开始起事务
                DB::beginTransaction();


                $Purchaseorder = Purchaseorder::query()->where('id',$datares['id'])->where('fid',$data['fid'])->update([
                        'fbillno'       => $data['fbillno']  ?? '',
                        'fbusinesstype'       => $data['fbusinesstype']  ?? '',
                        'fpurchaseorgid_number'       => $data['fpurchaseorgid_number']  ?? '',
                        'fpurchaseorgid_name'       => $data['fpurchaseorgid_name']  ?? '',
                        'fsupplierid_number'       => $data['fsupplierid_number']  ?? '',
                        'fsupplierid_name'       => $data['fsupplierid_name']  ?? '',
                        'fdocumentstatus'       => $data['fdocumentstatus']  ?? '',
                        'fforbidstatus'       => $data['fforbidstatus']  ?? '',
                        'fprovidercontactid'       => $data['fprovidercontactid']  ?? '',
                        'fproviderphone'       => $data['fproviderphone']  ?? '',
                    ]);
    
                // $Purchaseorder = Purchaseorder::query()->updateOrCreate(['fid' => $datares['fid']], [
                //     'fbillno'       => $data['fbillno']  ?? '',
                //     'fbusinesstype'       => $data['fbusinesstype']  ?? '',
                //     'fpurchaseorgid'       => $data['fpurchaseorgid']  ?? '',
                //     'fsupplierid_number'       => $data['fsupplierid_number']  ?? '',
                //     'fsupplierid_name'       => $data['fsupplierid_name']  ?? '',
                //     'fdocumentstatus'       => $data['fdocumentstatus']  ?? '',
                //     'fforbidstatus'       => $data['fforbidstatus']  ?? '',
                //     'fprovidercontactid'       => $data['fprovidercontactid']  ?? '',
                //     'fproviderphone'       => $data['fproviderphone']  ?? '',
                // ]);

                $Purchaseorderschedule = Purchaseorderschedule::query()->select('id','fentryid')->where('purchaseorder_id',$datares['id'])->where('fid',$data['fid'])->get()->toArray();
             
                    //删除成功
                    $result = [];
                    $fentryid = [];
                    $absent = [];
                    foreach($data['FEntry'] as $k=>$v){
                        $fentryid[] = $v['fentryid'];
                    }
                  
                    $Purchaseorderschedule_fentryid = [];
                    foreach($Purchaseorderschedule as $k=>$v){
                        $Purchaseorderschedule_fentryid[] = $v['fentryid'];
                    }
                    
                    foreach($Purchaseorderschedule as $key => $val ){
                        if(in_array($val['fentryid'], $fentryid)){
                            array_push($result, $val['fentryid']);
                        }else{
                            //删除数据库匹配不了的值
                        $absent[] = $val['fentryid'];
                        }
                    }
                  
                    
                    $data_SalesoutAttached = [];
                    $absent_fentryid = [];
                    
                    foreach($data['FEntry'] as $key => $val ){
                        if(in_array($val['fentryid'], $Purchaseorderschedule_fentryid)){
                            array_push($data_SalesoutAttached, $val['fentryid']);
                        }else{
                            //新加匹配不了的的数据库
                            $absent_fentryid[] = $val['fentryid'];
                        }
                    }
                    
                   
                    
                    if(!empty($result)){
                        //要修改的数据
                        $resultdata = [];
                        foreach ($result as $k=>$v){
                            $resultdata[$v] = $v;
                        }
                    }
            
                    
                    //要删的数据
                    if(!empty($absent)){
                        $deledata = [];
                        foreach ($absent as $k=>$v){
                            $Purchaseorderschedule_id = Purchaseorderschedule::query()->select('id')->select('id')->where('purchaseorder_id',$datares['id'])->where('fid',$data['fid'])->where('fentryid',$v)->first();
                        Purchaseorderschedule::query()->where('id',$Purchaseorderschedule_id['id'])->delete();
                        }   

                    }
                    

                    //要删添加的数据
                    if(!empty($absent_fentryid)){
                    $Addeddata = [];
                        foreach ($absent_fentryid as $k=>$v){
                            $Addeddata[$v] = $v;
                        }  
                    }

              
                foreach ($data['FEntry'] as $k=>$v){
                
                        //修改的数据
                    if(!empty($resultdata)){
                        
                        if(isset($resultdata[$v['fentryid']])){
                            $SalesoutAttached = Purchaseorderschedule::query()->select('id')->where('purchaseorder_id',$datares['id'])->where('fid',$data['fid'])->where('fentryid',$v['fentryid'])->first();
                                if(empty($SalesoutAttached)){
                                    throw new FailedException('单据体出错');
                                }
                                $Purchaseorderschedule = Purchaseorderschedule::query()->where('id', $SalesoutAttached['id'])->update(
                                    [
                                    'fid'=>$v['fid'],
                                    'fseq'=>$v['fseq'],
                                    // 'fentryid'=>$v['fentryid'],
                                    'fmaterialid'=>$v['fmaterialid'],
                                    'fmaterialname'=>$v['fmaterialname'],
                                    'fmaterialmodel'=>$v['fmaterialmodel'],
                                    'fmodel'=>$v['fmodel'],
                                    'funitid_number'=>$v['funitid_number'],
                                    'funitid_name'=>$v['funitid_name'],
                                    'fqty'=>$v['fqty'],
                                    'fdeliverydate'=>$v['fdeliverydate'],
                                    'fmemo'=>$v['fmemo'],
                                    'fownertypeid'=>$v['fownertypeid'],
                                    'fownerid_number'=>$v['fownerid_number'],
                                    'fownerid_name'=>$v['fownerid_name'],
                                    ]
                                );   
                            
                        }
                    }
                    
                    //新加的数据
                    if(!empty($Addeddata)){
                       
                            if(isset($Addeddata[$v['fentryid']])){
                               

                                Purchaseorderschedule::insert(
                                    [
                                        'purchaseorder_id'=>$datares['id'],
                                        'fid'=>$v['fid'],
                                        'fseq'=>$v['fseq'],
                                        'fentryid'=>$v['fentryid'],
                                        'fmaterialid'=>$v['fmaterialid'],
                                        'fmaterialname'=>$v['fmaterialname'],
                                        'fmaterialmodel'=>$v['fmaterialmodel'],
                                        'fmodel'=>$v['fmodel'],
                                        'funitid_number'=>$v['funitid_number'],
                                        'funitid_name'=>$v['funitid_name'],
                                        'fqty'=>$v['fqty'],
                                        'fdeliverydate'=>$v['fdeliverydate'],
                                        'fmemo'=>$v['fmemo'],
                                        'fownertypeid'=>$v['fownertypeid'],
                                        'fownerid_number'=>$v['fownerid_number'],
                                        'fownerid_name'=>$v['fownerid_name'],
                                        'updated_at'=>time(),
                                        'created_at'=>time()
                                    ]
                                    );
                            }
                    }
                    
                }
                // purchaseorderschedule::where('fid',$data['fid'])->delete();
                // $Purchaseorder->detailscheckAll()->createMany();
                DB::commit();
                return ['code'=>1000,'message'=>'修改成功'];
            } catch (\Exception $e) {
                DB::rollBack();
                throw new FailedException('数据修改失败，服务器上火星了请联系技术处理');
            }
    
    }

    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Purchaseorder::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            Purchaseorder::query()->where('fid',$id)->delete();
            Purchaseorderschedule::query()->where('fid',$id)->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }

}
